
//
//  AppDelegate.m
//  LookScore
//
//  Created by wr on 2017/12/4.
//  Copyright © 2017年 ChongQingXunTiCompany. All rights reserved.
//

#import "AppDelegate.h"
#import <BaiduMobStat.h>//百度统计
#import "LSUserGuideViewController.h"//引导页
#import "LSBaseTabBarController.h"//tabBar
#import <IQKeyboardManager.h>
#import "LSHttpEnclosureTool.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "LSCompetitionModel.h"
#import "CommonClass.h"
#import "WXApi.h"
#import "UIViewController+XYSideCategory.h"
#import "XYSideViewController.h"
#import "LSMineVController.h"
//#import "WRNavigationBar.h"
#import <AFNetworkActivityIndicatorManager.h>
#import <SDWebImageDownloaderOperation.h>
#import <CoreTelephony/CTCellularData.h>
#import "LSBaseViewController.h"
@interface AppDelegate ()<QQApiInterfaceDelegate,WXApiDelegate>
@property (nonatomic, strong) LSMineVController * leftVC;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    CTCellularData *cellularData = [[CTCellularData alloc]init];
    cellularData.cellularDataRestrictionDidUpdateNotifier =  ^(CTCellularDataRestrictedState state){
        //获取联网状态
        switch (state) {
            case kCTCellularDataRestricted:
                MyLog(@"Restricrted");
                break;
            case kCTCellularDataNotRestricted:
                MyLog(@"Not Restricted");
                break;
            case kCTCellularDataRestrictedStateUnknown:
                MyLog(@"Unknown");
                break;
            default:
                break;
        };
    };
    
    
    UIWindow *window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window = window;
    [window makeKeyAndVisible];
    [IQKeyboardManager sharedManager].enable = YES;
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    self.window.rootViewController = [[LSBaseViewController alloc] init];
//    [self loadConfig];
//    [self joinUserGuide];//引导页
    
    //判断关注的赛事是否为前一天关注的。
    for (LSCompetitionModel * model in [LSCompetitionModel findAll]) {
        if ([CommonClass getDaysFrom:[CommonClass StringTODate:model.currentTime] To:[CommonClass StringTODate:[CommonClass getCurrentTimes]]] >= 1) {
            [model deleteObject];
            [LSAccountArchive deletctEventWithEventId:model.MatchId];
        }
    }
    //注册微信
    [WXApi registerApp:@"wxb36fec60af8a29dd"];
//    [LSHttpEnclosureTool updateApiDomain];
    
//    SDWebImageDownloader *imgDownloader = SDWebImageManager.sharedManager.imageDownloader;
//    imgDownloader.headersFilter  = ^NSDictionary *(NSURL *url, NSDictionary *headers) {
//
//        NSFileManager *fm = [[NSFileManager alloc] init];
//        NSString *imgKey = [SDWebImageManager.sharedManager cacheKeyForURL:url];
//        NSString *imgPath = [SDWebImageManager.sharedManager.imageCache defaultCachePathForKey:imgKey];
//        NSDictionary *fileAttr = [fm attributesOfItemAtPath:imgPath error:nil];
//
//        NSMutableDictionary *mutableHeaders = [headers mutableCopy];
//
//        NSDate *lastModifiedDate = nil;
//
//        if (fileAttr.count > 0) {
//            if (fileAttr.count > 0) {
//                lastModifiedDate = (NSDate *)fileAttr[NSFileModificationDate];
//            }
//
//        }
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
//        formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
//        formatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss z";
//
//        NSString *lastModifiedStr = [formatter stringFromDate:lastModifiedDate];
//        lastModifiedStr = lastModifiedStr.length > 0 ? lastModifiedStr : @"";
//        [mutableHeaders setValue:lastModifiedStr forKey:@"If-Modified-Since"];
//
//        return mutableHeaders;
//    };
//
    
    
//    JANALYTICSLaunchConfig * config = [[JANALYTICSLaunchConfig alloc] init];
//    
//    config.appKey = @"5a27ea81bd32b5192f832c39";
//    
//    config.channel = @"channel";
//    
//    [JANALYTICSService setupWithConfig:config];
//    
//    [JANALYTICSService crashLogON];
//    
//    [JANALYTICSService setDebug:NO];
    
    [self startBaiduMobileStat];
    
//    if (@available(iOS 11.0, *)) {
//        
//        UITableView.appearance.estimatedRowHeight = 0;
//        UITableView.appearance.estimatedSectionHeaderHeight = 0;
//        UITableView.appearance.estimatedSectionFooterHeight = 0;
//    }
//    
    return YES;
}

/**
 
 启动百度移动统计
 
 */

- (void)startBaiduMobileStat{
    
    
    
    BaiduMobStat* statTracker = [BaiduMobStat defaultStat];
    statTracker.enableDebugOn = YES;
    statTracker.enableExceptionLog = YES; //是否允许截获并发送崩溃信息，请设置YES或者NO
    statTracker.channelId = @"AppStore";//设置您的app的发布渠道
    statTracker.logStrategy = BaiduMobStatLogStrategyAppLaunch ; //每次程序启动时发送（默认策略，推荐使用!）
    statTracker.logSendInterval = 1;  //为1时表示发送日志的时间间隔为1小时
    statTracker.logSendWifiOnly = YES; //是否仅在WIfi情况下发送日志数据
    statTracker.sessionResumeInterval = 60;//设置应用进入后台再回到前台为同一次session的间隔时间[0~600s],超过600s则设为600s，默认为30s
    statTracker.shortAppVersion  = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];//从CFBundleVersion里取app版本信息
    [statTracker startWithAppId:@"d603af51a8"]; // 设置您在mtj网站上添加的app的appkey,此处AppId即为应用的appKey
}


//-(void)sdWebImageConfig{
//
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sdWebImageDownloadReceiveResponseNotification:)name:SDWebImageDownloadReceiveResponseNotification object:nil];
//
//    SDWebImageDownloader *imgDownloader =SDWebImageManager.sharedManager.imageDownloader;
//    imgDownloader.headersFilter  = ^NSDictionary *(NSURL *url, NSDictionary*headers) {
//
//        NSMutableDictionary *mutableHeaders = [headers mutableCopy];
//
//        NSString * lastModifiedStr = [[SBAppCoreInfo getCacheDB]getStrValue:EMGlobal_LastModified_Cache  dataKey:url.absoluteString];
//        NSString * etagStr = [[SBAppCoreInfo getCacheDB]getStrValue:EMGlobal_ETag_Cache  dataKey:url.absoluteString];
//
//        [mutableHeaders setValue:lastModifiedStr forKey:@"If-Modified-Since"];
//        [mutableHeaders setValue:etagStr forKey:@"If-None-Match"];
//
//        return mutableHeaders;
//    };
//}

//-(void)sdWebImageDownloadReceiveResponseNotification:(NSNotification *)note{
//    SDWebImageDownloaderOperation *  downloaderOperation = (SDWebImageDownloaderOperation *)note.object;
//    NSString * urlKey = downloaderOperation.request.URL.absoluteString;
//    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)downloaderOperation.response;
//    //缓存Last-Modified、ETag值
//    [[SBAppCoreInfo getCacheDB] setStrValue:EMGlobal_LastModified_CachedataKey:urlKey dataValue:httpResponse.allHeaderFields[@"Last-Modified"]];
//    [[SBAppCoreInfo getCacheDB] setStrValue:EMGlobal_ETag_Cache dataKey:urlKeydataValue:httpResponse.allHeaderFields[@"ETag"]];
//}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    if ([url.scheme isEqualToString:[NSString stringWithFormat:@"tencent%@",@"101489380"]]) {
        [QQApiInterface handleOpenURL:url delegate:self];
        return [TencentOAuth HandleOpenURL:url];
    }else{
        
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    
    if ([url.scheme isEqualToString:[NSString stringWithFormat:@"tencent%@",@"101489380"]]) {
        return [TencentOAuth HandleOpenURL:url];
    }else{
        
        return [WXApi handleOpenURL:url delegate:self];
    }
   
    
}


- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    if ([url.scheme isEqualToString:[NSString stringWithFormat:@"tencent%@",@"101489380"]]) {
       return [TencentOAuth HandleOpenURL:url];
    }
    return [WXApi handleOpenURL:url delegate:self];
    
}
#pragma mark -- qq & weixin
- (void)onReq:(id)req{
    if ([req isKindOfClass:[SendMessageToWXReq class]]) {
        //微信
        
    }else{
        //qq
        
        
    }
    
}

- (void)onResp:(id)resp{
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        //微信
        SendMessageToWXResp * tmpResp = (SendMessageToWXResp *)resp;
        if (tmpResp.errCode == WXSuccess) {
            //分享成功
        }
    }else if ([resp isKindOfClass:[SendMessageToQQResp class]]){
        //qq
        SendMessageToQQResp * tmpResp  = (SendMessageToQQResp *)resp;
        if (tmpResp.type == ESENDMESSAGETOQQRESPTYPE && [tmpResp.result integerValue] == 0) {
            
        }
    }else if ([resp isKindOfClass:[SendAuthResp class]]){
         SendAuthResp *temp = (SendAuthResp *)resp;
        if (temp.errCode == 0) {
            [notifiCenter postNotificationName:@"threeLoginSuccess" object:temp];
        }
        
    }
    
}

- (void)isOnlineResponse:(NSDictionary *)response{
    
    
}




- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
